package com.px.user.service;

import com.px.common.util.sensi.SensitiveFilter;
import com.px.user.entity.Sensi;
import com.px.user.mapper.SensiMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Service
public class SensiService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SensiMapper sensiMapper;

    @Value("${px.notify.sensi-string}")
    private String sensiString;

    private SensitiveFilter sensitiveFilter;

    @PostConstruct
    public void startup()
    {
        String sensiStr = redisTemplate.opsForValue().get(sensiString);
        if (sensiStr != null){
            sensitiveFilter = new SensitiveFilter(sensiStr);
        }else {
            sensiSync();
        }
    }

    void initSensi() {
        String sensiStr = redisTemplate.opsForValue().get(sensiString);
        if (sensiStr != null){
            sensitiveFilter = new SensitiveFilter(sensiStr);
        }
    }

    public void sensiInsert(Sensi sensi) {
        sensiMapper.insert(sensi);
        sensiSync();
        initSensi();
    }

    public void sensiUpdate(Sensi sensi) {
        sensiMapper.update(sensi);
        sensiSync();
        initSensi();
    }

    public void sensiSync() {
        List<Sensi> sensis = sensiMapper.findAll();
        StringBuilder sb = new StringBuilder();
        sensis.forEach(r -> sb.append(r.getTxt()).append(System.lineSeparator()));
        redisTemplate.opsForValue().set(sensiString, sb.toString());
    }

    public String sensiFilter(String msg) {
        return sensitiveFilter.filter(msg, '*');
    }
}
